﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml;
using Microsoft.Practices.Prism.Mvvm;
using Microsoft.Practices.Prism.Mvvm.Interfaces;
using Microsoft.Practices.Prism.PubSubEvents;
using Microsoft.Practices.Unity;

namespace dwindleUrl
{
    public sealed partial class App : MvvmAppBase
    {
        public static INavigationService NavService;
        private readonly UnityContainer _container = new UnityContainer();
        private readonly IEventAggregator _eventAggregator = new EventAggregator();

        public App()
        {
            this.InitializeComponent();
        }

        protected override void OnRegisterKnownTypesForSerialization()
        {
            SessionStateService.RegisterKnownType(typeof(Models.Item));
        }

        protected override Task OnInitializeAsync(IActivatedEventArgs args)
        {
            _container.RegisterInstance<INavigationService>(this.NavigationService);
            _container.RegisterType<Repositories.IItemRepository, Repositories.ItemRepository>(
                new ContainerControlledLifetimeManager());
            _container.RegisterType<Repositories.IShortenerRepository, Repositories.ShortenerRepository>(
                new ContainerControlledLifetimeManager());
            _container.RegisterInstance<IEventAggregator>(this._eventAggregator);
            return Task.FromResult<object>(null);
        }

        protected override object Resolve(Type type)
        {
            return _container.Resolve(type);
        }

        protected override Task OnLaunchApplicationAsync(LaunchActivatedEventArgs args)
        {
            var timer = new DispatcherTimer() { Interval = TimeSpan.FromSeconds(1) };
            timer.Tick += (s, e) =>
            {
                _eventAggregator.GetEvent<Message.NewValue>()
                    .Publish((int)DateTime.Now.Second);
            };
            timer.Start();

            this.NavigationService.Navigate("Dwindle", null);
            return Task.FromResult<object>(null);
        }

#if WINDOWS_APP
        protected override IList<Windows.UI.ApplicationSettings.SettingsCommand> GetSettingsCommands()
        {
            var command = new Windows.UI.ApplicationSettings
            .SettingsCommand(Guid.NewGuid(), "About", e =>
            {

                new Views.AboutPage().ShowIndependent();
            });

            return new[] { command };
        }
#endif
    }
}